package com.example.demo.zaqizabatest.多线程相关;

/**
 * @ClassName 龟兔赛跑
 * @Author lys4134
 * @Date 2021/08/27 10:53:46
 * @Description 龟兔赛跑
 * <p>
 * 龟兔赛跑：2000米
 * 要求：
 * (1)兔子每 0.1 秒 5 米的速度，每跑20米休息1秒;
 * (2)乌龟每 0.1 秒跑 2 米，不休息；
 * (3)其中一个跑到终点后另一个不跑了！
 * @Version 1.0
 **/
@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public class 龟兔赛跑 {
    private volatile static int tuzi = 0;
    private volatile static int wugui = 0;

    private static void tuziRun() throws InterruptedException {
        while (tuzi < 2000) {
            if (wugui >= 2000) {
                System.out.println("兔子共跑了" + tuzi + "米");
                System.out.println("乌龟已经到达终点，乌龟赢了");
                return;
            }
            if (tuzi != 0 && tuzi % 20 == 0) {
                Thread.sleep(1000);
            } else {
                tuzi += 5;
                Thread.sleep(100);
                System.out.println("兔子跑了" + tuzi + "米，距离终点还有" + (2000 - tuzi) + "米");

            }
        }


    }

    private static void wuguiRun() throws InterruptedException {
        while (wugui < 2000) {
            if (tuzi >= 2000) {
                System.out.println("乌龟共跑了" + wugui + "米");
                System.out.println("兔子已经到达终点，兔子赢了");
                return;
            }
            wugui += 2;
            Thread.sleep(100);
            System.out.println("乌龟跑了" + wugui + "米，距离终点还有" + (2000 - wugui) + "米");
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                wuguiRun();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "乌龟").start();
        new Thread(() -> {
            try {
                tuziRun();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "兔子").start();
    }
}
